package com.android.delivery.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import com.android.delivery.R
import com.android.delivery.api.ApiService
import com.android.delivery.base.BaseActivity
import com.android.delivery.callback.DialogCallback
import com.android.delivery.callback.LzyResponse
import com.android.delivery.constant.Constants
import com.android.delivery.entity.Addr
import com.android.delivery.entity.Logistics
import com.android.delivery.entity.request.OrderReq
import com.android.delivery.util.ToastUtils
import com.honghu.villagepost.entity.request.LogisticsOrderDetail
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_order_settle.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @author: mqwang
 * @create: 3/23/21 12:10 AM
 * @Description: 创建订单
 */
class OrderSettleActivity : BaseActivity() {

    /** 0-寄件，1-收件*/
    private var selectAddrType: Int = 0

    //是否是修改订单
    private var isFromModify: Boolean = false

    private var mType: Int = 1

    companion object {
        val TYPE_SEND: Int = 1//速配寄件
        val TYPE_LINDAN_SEND: Int = 2//零担寄件
        val TYPE_CITY_SEND: Int = 3//同城速递
        fun self(context: Activity?, type: Int, logistics: OrderReq) {
            val intent = Intent(context, OrderSettleActivity::class.java)
            intent.putExtra(Constants.ITEM, logistics)
            intent.putExtra(Constants.TYPE, type)
            context!!.startActivity(intent)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_order_settle
    }

    override fun isBindEventBus(): Boolean {
        return true
    }

    override fun init(savedInstanceState: Bundle?, container: View?) {
        mType = intent.getIntExtra(Constants.TYPE, 1)
        var logisticsOrderReq = intent.getParcelableExtra<OrderReq>(Constants.ITEM)
        if (logisticsOrderReq != null) {
            setMainTitle("修改订单")
            isFromModify = true
            mLogisticsOrderReq = logisticsOrderReq
            val senderAddr = logisticsOrderReq?.senderAddress
            if (senderAddr != null && !TextUtils.isEmpty(senderAddr.name)) {
                tv_send_name.setText(senderAddr.name)
                tv_send_phone.setText(senderAddr.mobile)
                tv_send_addr.setText(senderAddr.city + senderAddr.district + senderAddr.street + senderAddr.address)
            }

            val receiverAddr = logisticsOrderReq?.receiverAddress
            if (receiverAddr != null && !TextUtils.isEmpty(receiverAddr.name)) {
                tv_receiver_name.setText(receiverAddr.name)
                tv_receiver_phone.setText(receiverAddr.mobile)
                tv_receiver_addr.setText(receiverAddr.city + receiverAddr.district + receiverAddr.street + receiverAddr.address)
            }

            if (logisticsOrderReq.payType == 1) {
                rb_jf.isChecked = true
                rb_df.isChecked = false
            } else if (logisticsOrderReq.payType == 2) {
                rb_jf.isChecked = false
                rb_df.isChecked = true
            }

            if (TextUtils.equals(rb_qp.text.toString(), logisticsOrderReq.goodsInfo)) {
                rb_qp.isChecked = true
                rb_sjpj.isChecked = false
                rb_sp.isChecked = false
                rb_qt.isChecked = false
            } else if (TextUtils.equals(rb_sjpj.text.toString(), logisticsOrderReq.goodsInfo)) {
                rb_qp.isChecked = false
                rb_sjpj.isChecked = true
                rb_sp.isChecked = false
                rb_qt.isChecked = false
            } else if (TextUtils.equals(rb_sp.text.toString(), logisticsOrderReq.goodsInfo)) {
                rb_qp.isChecked = false
                rb_sjpj.isChecked = false
                rb_sp.isChecked = true
                rb_qt.isChecked = false
            } else if (TextUtils.equals(rb_qt.text.toString(), logisticsOrderReq.goodsInfo)) {
                rb_qp.isChecked = false
                rb_sjpj.isChecked = false
                rb_sp.isChecked = false
                rb_qt.isChecked = true
            }
            settleOrder()
            getOrderDetail(logisticsOrderReq.logisticsNo)
        } else {
            setMainTitle("创建订单")
        }

        tv_ji_addr.setOnClickListener {
            selectAddrType = 0
            AddrActivity.self(this, true)
        }
        send_layout.setOnClickListener {
            selectAddrType = 0
            if (mLogisticsOrderReq != null && mLogisticsOrderReq.senderAddress != null) {
                AddAddrActivity.self(this, mLogisticsOrderReq.senderAddress)
            } else {
                AddAddrActivity.self(this)
            }
        }

        tv_shou_addr.setOnClickListener {
            selectAddrType = 1
            AddrActivity.self(this, true)
        }
        receiver_layout.setOnClickListener {
            selectAddrType = 1
            if (mLogisticsOrderReq != null && mLogisticsOrderReq.receiverAddress != null) {
                AddAddrActivity.self(this, mLogisticsOrderReq.receiverAddress)
            } else {
                AddAddrActivity.self(this)
            }
        }

        rg_wplx.setOnCheckedChangeListener { group, checkedId ->
            settleOrder()
        }

        rg_type.setOnCheckedChangeListener { group, checkedId ->
            settleOrder()
        }

        val czfy = et_czfy.text.toString()
        if (!TextUtils.isEmpty(czfy)) {
            et_czfy.setSelection(czfy.length)
        }
        et_czfy.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                if (!TextUtils.isEmpty(s.toString())) {
                    settleOrder()
                }
            }

        })
        tv_confirm.setOnClickListener {
            if (mLogisticsOrderReq.senderAddress != null &&
                    !TextUtils.isEmpty(mLogisticsOrderReq.senderAddress.name) &&
                    mLogisticsOrderReq.receiverAddress != null &&
                    !TextUtils.isEmpty(mLogisticsOrderReq.receiverAddress.name)) {

                val userBz = et_bz.text.toString()
                mLogisticsOrderReq.userMemo = userBz

                if (isFromModify) {
                    ApiService.order_modify(this, mLogisticsOrderReq, mType, object : DialogCallback<LzyResponse<Any>>(this) {
                        override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                            //如果是修改，发送通知刷新列表
                            EventBus.getDefault().post(mLogisticsOrderReq)
//                            OrderDetailsActivity.self(mContext, mLogisticsOrderReq.logisticsNo)
                            ToastUtils.showShort(this@OrderSettleActivity, "订单修改成功")
                            finish()
                        }
                    })
                } else {
                    ApiService.order_create(this, mLogisticsOrderReq, mType, object : DialogCallback<LzyResponse<Logistics>>(this) {
                        override fun onSuccess(response: Response<LzyResponse<Logistics>>?) {
                            val data = response?.body()?.data
                            if (data != null) {
//                                OrderDetailsActivity.self(mContext, data.logisticsNo!!)
                                ToastUtils.showShort(this@OrderSettleActivity, "下单成功")
                                finish()
                            }
                        }
                    })
                }
            } else {
                ToastUtils.showShort(this, "请补全订单信息")
            }
        }

        iv_add.setOnClickListener {
            var money = 0
            if (!TextUtils.isEmpty(et_czfy.text)) {
                money = et_czfy.text.toString().toInt()
            }
            et_czfy.setText((money + 1).toString())
            et_czfy.setSelection(et_czfy.text.toString().length)
            settleOrder()
        }

        iv_reduce.setOnClickListener {
            var money = 0
            if (!TextUtils.isEmpty(et_czfy.text)) {
                money = et_czfy.text.toString().toInt()
            }
            if (money > 0) {
                money = money - 1
            }

            et_czfy.setText(money.toString())
            et_czfy.setSelection(et_czfy.text.toString().length)
            settleOrder()
        }
    }

    private fun getOrderDetail(logisticsNo: String) {
        ApiService.order_details(this, logisticsNo, object : DialogCallback<LzyResponse<LogisticsOrderDetail>>() {
            override fun onSuccess(response: Response<LzyResponse<LogisticsOrderDetail>>?) {
                val orderDetail = response!!.body().data
                if (!TextUtils.isEmpty(orderDetail.userMemo)) {
                    et_bz.setText(orderDetail.userMemo)
                    et_bz.setSelection(orderDetail.userMemo.length)
                    mLogisticsOrderReq.userMemo = orderDetail.userMemo
                }

                val excessWeightFee = orderDetail.excessWeightFee.toInt().toString()
                if (!TextUtils.isEmpty(excessWeightFee)) {
                    et_czfy.setText(excessWeightFee)
                    et_czfy.setSelection(excessWeightFee.length)
                    mLogisticsOrderReq.excessWeightFee = orderDetail.excessWeightFee
                }
                settleOrder()
            }
        })
    }

    fun settleOrder() {
        if (mLogisticsOrderReq.senderAddress != null &&
                !TextUtils.isEmpty(mLogisticsOrderReq.senderAddress.name) &&
                mLogisticsOrderReq.receiverAddress != null &&
                !TextUtils.isEmpty(mLogisticsOrderReq.receiverAddress.name)) {
            if (rb_jf.isChecked) {
                mLogisticsOrderReq.payType = 1
            } else {
                mLogisticsOrderReq.payType = 2
            }

            if (rb_qp.isChecked) {
                mLogisticsOrderReq.goodsInfo = rb_qp.text.toString()
            } else if (rb_sjpj.isChecked) {
                mLogisticsOrderReq.goodsInfo = rb_sjpj.text.toString()
            } else if (rb_sp.isChecked) {
                mLogisticsOrderReq.goodsInfo = rb_sp.text.toString()
            } else {
                mLogisticsOrderReq.goodsInfo = rb_qt.text.toString()
            }
            mLogisticsOrderReq.excessWeightFee = et_czfy.text.toString().toDouble()

            ApiService.order_settle(this, mLogisticsOrderReq, mType, object : DialogCallback<LzyResponse<OrderReq>>() {
                override fun onSuccess(response: Response<LzyResponse<OrderReq>>?) {
                    tv_jcfy.setText(getString(R.string.price_format, response!!.body().data.baseFee))
                    tv_qjfy.setText(getString(R.string.price_format, response!!.body().data.excessDistancePickFee))
                    tv_pjfy.setText(getString(R.string.price_format, response!!.body().data.excessDistanceDeliveryFee))
                    tv_zfy.setText(getString(R.string.price_format, response!!.body().data.totalFee))

                }
            })
        }
    }

    private var mLogisticsOrderReq: OrderReq = OrderReq()

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun addrEven(item: Addr) {
        when (selectAddrType) {
            0 -> {
                tv_send_name.setText(item.name)
                tv_send_phone.setText(item.mobile)
                tv_send_addr.setText(item.city + item.district + item.street + item.address)
                mLogisticsOrderReq.senderAddress = item

                settleOrder()
            }
            1 -> {
                tv_receiver_name.setText(item.name)
                tv_receiver_phone.setText(item.mobile)
                tv_receiver_addr.setText(item.city + item.district + item.street + item.address)
                mLogisticsOrderReq.receiverAddress = item

                settleOrder()

            }
        }
    }


}